#!/usr/bin/env python
import SocketServer

class IcarusConsoleServer(SocketServer.TCPServer):
	def __init__(self, server_address, RequestHandlerClass, state):
		SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)
		self.state = state

class ConsoleHandler(SocketServer.StreamRequestHandler):
	# Command reader
	def handle(self):
		while True:
			try:
				# Get a command from console
				cmd = self.rfile.readline()

				# Process exit command anyway
				if cmd.strip() == 'exit':
					self.wfile.write("Bye-bye\n")
					break

				# Just reply something
				self.server.state['last_console_cmd'] = cmd
				self.wfile.write("Got a command: ")
				self.wfile.write(cmd)
			except IOError:
				pass




def Run(state):
	server = IcarusConsoleServer((state['config']['console']['listen_addr'], state['config']['console']['listen_port']), ConsoleHandler, state)
	server.serve_forever()

# End-of-file
